import inspect
from contextlib import asynccontextmanager
from importlib import import_module

from fastapi import FastAPI, APIRouter
from fastapi.middleware.cors import CORSMiddleware

from settings import APPS_LIST


def include_apps(_: FastAPI):
    """
    注册所有模块
    :param _: 全局app对象
    """
    # 循环apps名称列表
    for APP in APPS_LIST:
        # 导入包
        model = import_module(APP)
        # 获取包内的所有成员
        for member_name, member_value in inspect.getmembers(model):
            # 判断类型是否APIRouter
            if isinstance(member_value, APIRouter):
                # 如果是则导入
                _.include_router(member_value)


@asynccontextmanager
async def lifespan(_: FastAPI):
    # 注册所有模块
    include_apps(_)
    yield


app = FastAPI(lifespan=lifespan)

origins = [
    "*"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == '__main__':
    import uvicorn

    uvicorn.run("main:app", host='0.0.0.0', port=8000, reload=True)

# alembic revision --autogenerate -m "first commit"
# alembic upgrade head
